<?php
// websocket.php 面向对象的编写
class Ws{
    private $host = '0.0.0.0';
    private $port = 9119;
    public $ws = null;
    public function __construct(){

        $this->ws = new swoole_websocket_server($this->host,$this->port);
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => '/home/centos/public_html/sw/demo/html',
            'task_worker_num' => 2
        ]);
        $this->ws->on('open',[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onClose']);
        $this->ws->start();
    }

    /**
     * 监听ws 连接事件
     */
    public function onOpen($ws,$request){
        var_dump('open - '.$request->fd);
        swoole_timer_tick(2000,function($timer_id){
            echo '2s:timerId:'.$timer_id."\n";
        });
    }

    /**
     * 监听ws 消息事件
     */
    public function onMessage($server,$frame){
        swoole_timer_after(5000,function() use($server,$frame){
            echo '5s-after'."\n";
            $server->push($frame->fd,"server-timer-after:\n");
        });
        $server->push($frame->fd,'来自服务器的推送：hello,joy - '.date('Y-m-d H:i:s',time()));
    }

    public function onTask($serv,$task_id,$src_worker_id,$data){
        var_dump( $task_id );
        var_dump( $src_worker_id );
        print_r( $data );
        sleep(10);
        return 'task 任务已经完成';
    }

    public function onFinish($serv,$task_id,$data){
        var_dump( $task_id );
        var_dump( $data );
    }

    /**
     * 监听关闭事件
     */
    public function onClose($server,$fd){
        echo 'close-clientid:'.$fd."\n";
    }
}

$obj = new Ws();